package com.gqh.weather.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * MinIO初始化
 * 容器启动完成后，自动创建bucket并设置下载权限
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MinioInit implements ApplicationRunner {

    private final MinioClient minioClient;
    private final MinioConfig minioConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("开始初始化MinIO...");
        
        // 初始化学生人脸存储桶
        initBucket(minioConfig.getBucketStudentFace());
        
        // 初始化临时存储桶
        initBucket(minioConfig.getTemp());
        
        log.info("MinIO初始化完成");
    }

    /**
     * 初始化存储桶：如果不存在则创建，并设置为可下载权限
     *
     * @param bucketName 存储桶名称
     */
    private void initBucket(String bucketName) throws Exception {
        try {
            // 检查bucket是否存在
            boolean exists = minioClient.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(bucketName)
                            .build()
            );

            // 如果不存在则创建
            if (!exists) {
                minioClient.makeBucket(
                        MakeBucketArgs.builder()
                                .bucket(bucketName)
                                .build()
                );
                log.info("创建bucket成功: {}", bucketName);
            } else {
                log.info("bucket已存在: {}", bucketName);
            }

            // 设置bucket权限为download（允许匿名下载）
            String policy = getDownloadPolicy(bucketName);
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(bucketName)
                            .config(policy)
                            .build()
            );
            log.info("设置bucket权限为download成功: {}", bucketName);
            
        } catch (Exception e) {
            log.error("初始化bucket失败: {}", bucketName, e);
            throw e;
        }
    }

    /**
     * 获取允许下载的bucket策略
     *
     * @param bucketName 存储桶名称
     * @return JSON格式的策略字符串
     */
    private String getDownloadPolicy(String bucketName) {
        return String.format(
                """
                {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"AWS": ["*"]},
                            "Action": ["s3:GetObject"],
                            "Resource": ["arn:aws:s3:::%s/*"]
                        }
                    ]
                }
                """,
                bucketName
        );
    }
}